
$(function () {

    //资源归属，一级公司
    $.ajax({
        url: ctx + '/department/getAllOption',
        data: {parentId: 0},
        dataType: 'json',
        type: 'post',
        success: function (data) {
            if (data.status != "success") {
                toastr.error(data.msg);
            } else {
                var opt = "<option value='0'>---请选择---</option>";

                for (var i = 0; i < data.list.length; ++i) {
                    opt += "<option value='" + data.list[i].departmentId + "'>" + data.list[i].fullName + "</option>";
                }

                $('#partnerAdd select[name="departmentId"]').html(opt);

            }
        },
        error: function () {
            toastr.error("系统错误");
        }
    });


    /**
     * 新增联系人名单、银行卡信息、返款账号信息
     * @param parentEle
     */
    function addField(parentEle) {
        $(parentEle).on('click', '.add-button', function () {
            //删除
            if ($(this).is('.fa-minus-circle')) {
                if ($(this).parent().parent().find('label').html() == '') {
                    $(this).parent().parent().remove();
                } else {
                    $(this).parent().parent().next().find('label').html($(this).parent().parent().find('label').html());
                    $(this).parent().parent().remove();
                }
            }
            //新增
            if ($(this).is('.fa-plus-circle')) {
                //联系人名单
                if ($(this).is('.linkmanAdd')) {
                    var link = $(this).parent().parent().clone(true);
                    $(link).find('input').val('');
                    $(link).find('input').eq(0).val("次要");
                    $(link).find('.linkmanAdd').show();

                    $(this).parent().parent().after(link);
                    $(parentEle).find('.contactList:not(:first)').find('label').html('');
                }

                //银行卡信息
                if ($(this).is('.bankcardAdd')) {
                    var bankcard = $(this).parent().parent().clone(true);
                    $(bankcard).find('input').val('');
                    $(bankcard).find('.bankcardAdd').show();

                    $(this).parent().parent().after(bankcard);
                    $(parentEle).find('.bankCard:not(:first)').find('label').html('');
                }

                //返款账号信息
                if ($(this).is('.rebatesAccount')) {
                    var rebatesAccount = $(this).parent().parent().clone(true);
                    $(rebatesAccount).find('input').val('');
                    $(rebatesAccount).find('.rebatesAccount').show();

                    $(this).parent().parent().after(rebatesAccount);
                    $(parentEle).find('.rebates:not(:first)').find('label').html('');
                }
            }
        });
    }

    //合作方新增
    addField('.partnerAdd');
    


    InitiateSimpleDataTable.init();


    //搜索
    $('#partner .search-btn').click(function () {
        InitiateSimpleDataTable.init();
    })

    //启用禁用
    $('#partnerTable').on('click', '.btn-use', function () {

        $.ajax({
            url: ctx + '/bizPartner/updateRecord',
            data: {partnerId: $(this).data('id'), enable: 0},
            dataType: 'json',
            type: 'post',
            success: function (data) {
                InitiateSimpleDataTable.init();
            },
            error: function () {
                toastr.error("系统错误");
            }
        });

    });

    $('#partnerTable').on('click', '.btn-nouse', function () {

        $.ajax({
            url: ctx + '/bizPartner/updateRecord',
            data: {partnerId: $(this).data('id'), enable: 1},
            dataType: 'json',
            type: 'post',
            success: function (data) {
                InitiateSimpleDataTable.init();
            },
            error: function () {
                toastr.error("系统错误");
            }
        });

    });

    
    //合同管理
    $('#partnerTable').on('click', '.contract', function () {
    	var partnerId = $(this).data('id');
    	loadHtml('/bizContract/index?partnerId='+partnerId);
    });
    
    
    //合作单位编辑
    $('#partnerTable').on('click', '.edit', function () {
    	$(".widget-caption").html("编辑");
        var record = $(this).data('record');

        //console.log(record);
        
        $('#partnerAdd input[name="partnerId"]').val(record.partnerId);

        $('#partnerAdd select[name="departmentId"]').val(record.departmentId);
        $('#partnerAdd input[name="partnerCode"]').val(record.partnerCode);
        $('#partnerAdd input[name="partnerName"]').val(record.partnerName);
        $('#partnerAdd input[name="partnerShortName"]').val(record.partnerShortName);
        $('#partnerAdd input[name="partnerAddress"]').val(record.partnerAddress);

        var contact = JSON.parse(record.contact);

        var contactDom = "";
        for (var i = 0; i < contact.length; ++i) {
                contactDom += '<div class="form-group col-sm-12 contactList">' +
                    '<label class="control-label col-sm-2 no-padding-right">联系人名单<span class="control-label mandatory">*</span></label>' +
                    '<div class="col-sm-10">' +
                    '<div class="col-sm-2 no-padding">' +
                    '<input name="type" value="'+contact[i].type+'" class="form-control" readonly="readonly">' +
                    '</div>' +
                    '<div class="col-sm-4">' +
                    '<input name="name" type="text" value="'+contact[i].name+'" class="form-control" placeholder="联系人姓名">' +
                    '</div>' +
                    '<div class="col-sm-5 no-padding-right">' +
                    '<input name="tel" type="text" value="'+contact[i].tel+'" class="form-control" placeholder="联系电话">' +
                    '</div>' +
                    '<i class="fa fa-plus-circle blue linkmanAdd control-label add-button"></i>' +
                    '<i class="fa fa-minus-circle danger linkmanAdd control-label add-button" style="display:inline;line-height: 33px;"></i>' +
                    '</div>' +
                    '</div>';
        }
        

        $('#partnerAdd .contactList').remove();
        $('#partnerAdd .contact-split').after(contactDom);
        $('#partnerAdd .contactList').find('.fa-minus-circle').eq(0).css('display', 'none');
        
        var bankCard = JSON.parse(record.bankCard);
        var bankCardDom = "";
        for (var i = 0; i < bankCard.length; ++i) {
        	bankCardDom += '<div class="form-group col-sm-12 bankCard">' +
			            '<label class="control-label col-sm-2 no-padding-right">银行卡信息<span class="control-label mandatory">*</span></label>' +
			            '<div class="col-sm-10">' +
			                '<div class="col-sm-2 no-padding">' +
			                    '<input name="bank" type="text" value="'+bankCard[i].bank+'" class="form-control" placeholder="开户行">' +
			                '</div>' +
			                '<div class="col-sm-4">' +
			                    '<input name="detail" value="'+bankCard[i].detail+'" type="text" class="form-control" placeholder="开户行名称">' +
			                '</div>' +
			                '<div class="col-sm-2">' +
			                    '<input name="user" type="text" value="'+bankCard[i].user+'" class="form-control" placeholder="开户人">' +
			                '</div>' +
			                '<div class="col-sm-3 no-padding">' +
			                    '<input name="account" type="text" value="'+bankCard[i].account+'" class="form-control" placeholder="账号">' +
			                '</div>' +
			                '<i class="fa fa-plus-circle blue bankcardAdd control-label add-button"></i>' +
			                '<i class="fa fa-minus-circle danger bankcardAdd control-label add-button" style="display:inline;line-height:33px;"></i>' +
			            '</div>' +
		            '</div>';
        }
        
        if(bankCardDom != ""){
        	$('#partnerAdd .bankCard').remove();
            $('#partnerAdd .bankCard-split').after(bankCardDom);
        }
        
        $('#partnerAdd .bankCard').find('.fa-minus-circle').eq(0).css('display', 'none');
        
        
        var bankReturn = JSON.parse(record.bankReturn);
        var bankReturnDom = "";
        for (var i = 0; i < bankReturn.length; ++i) {
        	bankReturnDom += '<div class="form-group col-sm-12 rebates">' +
			            '<label class="control-label col-sm-2 no-padding-right">返款账号信息<span class="control-label mandatory">*</span></label>' +
			            '<div class="col-sm-10">' +
			                '<div class="col-sm-2 no-padding">' +
			                    '<input name="bank" type="text" value="'+bankReturn[i].bank+'" class="form-control" placeholder="开户行">' +
			                '</div>' +
			                '<div class="col-sm-4">' +
			                    '<input name="detail" value="'+bankReturn[i].detail+'" type="text" class="form-control" placeholder="开户行名称">' +
			                '</div>' +
			                '<div class="col-sm-2">' +
			                    '<input name="user" type="text" value="'+bankReturn[i].user+'" class="form-control" placeholder="开户人">' +
			                '</div>' +
			                '<div class="col-sm-3 no-padding">' +
			                    '<input name="account" type="text" value="'+bankReturn[i].account+'" class="form-control" placeholder="账号">' +
			                '</div>' +
			                '<i class="fa fa-plus-circle blue bankcardAdd control-label add-button"></i>' +
			                '<i class="fa fa-minus-circle danger bankcardAdd control-label add-button" style="display:inline;line-height:33px"></i>' +
			            '</div>' +
		            '</div>';
        }
        
        if(bankReturnDom != ""){
        	$('#partnerAdd .rebates').remove();
            $('#partnerAdd .bankReturn-split').after(bankReturnDom);
        }
        
        $('#partnerAdd .rebates').find('.fa-minus-circle').eq(0).css('display', 'none');
        
        $('.partnerAdd').modal('show');
    });
    
    
    //新增合作人
    $('.partnerAdd').on('hidden.bs.modal', function () {
    	$(".widget-caption").html("新增");
    	$('#partnerAdd')[0].reset();
    	
    	
    	$('#partnerAdd input:hidden').val('');
    	$('#partnerAdd .contactList').find('input').val('');
    	$('#partnerAdd .bankCard').find('input').val('');
    	$('#partnerAdd .rebates').find('input').val('');
    	$('#partnerAdd .contactList').find('input').eq(0).val("首要");

        $('#partnerAdd .contactList:not(:eq(0))').remove();

        $('#partnerAdd .bankCard:not(:eq(0))').remove();

        $('#partnerAdd .rebates:not(:eq(0))').remove();
        
        $('#partnerAdd input:submit').removeAttr('disabled');
        
        $('#partnerAdd input:submit').val('确定');
        
    })

    $('#partnerAdd').on('focusin', 'input,select', function(){
    	$('#partnerAdd input:submit').removeAttr('disabled');
    });
    
    
})

function retrieveData(sSource, aoData, fnCallback, oSettings) {

    aoData.push({"name": "pageNum", "value": (Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1)});
    aoData.push({"name": "pageSize", "value": oSettings._iDisplayLength});

    var searchVal = $('#partner .searchVal').val();

    if (searchVal && searchVal.length != 0) {
        aoData.push({"name": "searchVal", "value": searchVal});
    }

    var enable = $('#partner select[name="status"]').val();


    if (enable == 0 || enable == 1) {
        aoData.push({"name": "enable", "value": enable});
    }

    $.ajax({
        "url": sSource,
        "data": aoData,
        "cache": false,
        "dataType": 'json',
        "type": "POST",
        "success": function (response) {
            fnCallback(response.returnObject);
        }
    });
}  


function validateForm(form, callback, confirmMsg){
	
	var contactArr = [];
    $('#partnerAdd input[name="name"]').each(function () {
        var i = $(this).index('#partnerAdd input[name="name"]');
        var contactObj = {};
        contactObj["name"] = $(this).val();
        contactObj['type'] = $('#partnerAdd input[name="type"]').eq(i).val();
	        contactObj["tel"] = $('#partnerAdd input[name="tel"]').eq(i).val();
        contactArr.push(contactObj);
    })

    var bankArr = [];
    $('#partnerAdd input[name="bank"]').each(function () {
        var i = $(this).index('#partnerAdd input[name="bank"]');
        var bankObj = {};
        bankObj["bank"] = $(this).val();
        bankObj['detail'] = $('#partnerAdd input[name="detail"]').eq(i).val();
        bankObj["user"] = $('#partnerAdd input[name="user"]').eq(i).val();
        bankObj["account"] = $('#partnerAdd input[name="account"]').eq(i).val();
        bankArr.push(bankObj);
    })

    var bankReturnArr = [];
    $('#partnerAdd input[name="bank_return"]').each(function () {
        var i = $(this).index('#partnerAdd input[name="bank_return"]');
        var bankReturnObj = {};
        bankReturnObj["bank"] = $(this).val();
        bankReturnObj['detail'] = $('#partnerAdd input[name="detail_return"]').eq(i).val();
        bankReturnObj["user"] = $('#partnerAdd input[name="user_return"]').eq(i).val();
        bankReturnObj["account"] = $('#partnerAdd input[name="account_return"]').eq(i).val();
        bankReturnArr.push(bankReturnObj);
    })

    var departmentId = $('#partnerAdd select[name="departmentId"]').val();
    var partnerCode = $('#partnerAdd input[name="partnerCode"]').val();
    var partnerName = $('#partnerAdd input[name="partnerName"]').val();
    var partnerShortName = $('#partnerAdd input[name="partnerShortName"]').val();
    var partnerAddress = $('#partnerAdd input[name="partnerAddress"]').val();
    var partnerId = $('#partnerAdd input[name="partnerId"]').val();
    
    var params = {};
    params['departmentId'] = departmentId;
    params['partnerCode'] = partnerCode;
    params['partnerName'] = partnerName;
    params['partnerShortName'] = partnerShortName;
    params['partnerAddress'] = partnerAddress;
    params['contact'] = JSON.stringify(contactArr);
    params['bankCard'] = JSON.stringify(bankArr);
    params['bankReturn'] = JSON.stringify(bankReturnArr);
    params['partnerId'] = partnerId;
    
    $('#partnerAdd input:submit').attr('disabled', 'disabled');
    $.ajax({
        url: ctx + '/bizPartner/addNewRecord',
        data: params,
        dataType: 'json',
        type: 'post',
        success: function (data) {
            if (data.status != "success") {
                toastr.error(data.msg);
            } else {
                $('.partnerAdd').modal('hide');
                InitiateSimpleDataTable.init();
            }
        },
        error: function () {
            toastr.error("系统错误");
        }
    });
	
	return false;
}
//回车搜索
function search(){
	if(event.keyCode==13){
		InitiateSimpleDataTable.init();
	}
}
